package com.yunxi.service.sap.dubbo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yunxi.bizToHub.pojo.*;
import com.yunxi.bizToHub.service.VehicleStockManageDubboService;
import com.yunxi.core.base.Constant;
import com.yunxi.core.util.HttpUtil;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.bizToHub.pojo.AssignedInfoVO;
import com.yunxi.model.eai.EaiLog;
import com.yunxi.rocketmq.producer.EaiLogsProducer;
import com.yunxi.service.ReturnResultMsg;
import com.yunxi.tech.pojo.OrderActualSalesReqVO;
import com.yunxi.tech.service.IamOrderActualSalesDubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;

import java.util.Date;
import java.util.Map;

/**
 * Created by xuruzi on 2019/6/1.
 */
public class VehicleStockManageDubboServiceImpl implements VehicleStockManageDubboService {
    protected static final Logger LOGGER = LoggerFactory.getLogger(VehicleStockManageDubboServiceImpl.class);

    @Autowired
    private EaiLogsProducer eaiLogsProducer;
    @Value("${esb.switch}")
    private String esbSwitch;
    @Value("${COMM.URL}")
    private String COMM_URL ;
    @Value("${SAP.URL}")
    private String SAP_URL;
    @Value("${TSP.URL}")
    private String TSP_URL;
    @Value("${COMM2.URL}")
    private String COMM2_URL;
    @Value("${TSP.TRANSFER.URL}")
    private String TSP_TRANSFER_URL;
    @Autowired
    private IamOrderActualSalesDubboService iamOrderActualSalesDubboServiceImpl;
    /**
     * 交货单过账pms->sap
     * @param order
     * @return
     */
    @Override
    public ApiResult vehicleDeliveryOrderPostingPms2Sap(VehicleDeliveryOrderPostingVO order) {
       /* if (true){
            order.setBudat("2019-07-01");
        }else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr=sdf.format(new Date());
            order.setBudat(dateStr);
        }*/
       /* SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr=sdf.format(new Date());
        order.setBudat(dateStr);
        order.setLgort("VW01");
        order.setWerks("AS11");*/
        String deliveryOrderInfo = JSONObject.toJSONString(order);
        ApiResult apiResult=null;
        EaiLog eaiLog=new EaiLog();
        eaiLog.setPmsEaiContent(deliveryOrderInfo);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("PMS系统发送交货单过账信息给SAP系统");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setServiceName(Constant.PMS_SAP_VEHICLE_DELIVERY_ORDER_POSTING);
        if (esbSwitch.equals("false")) {
            return ResponseUtil.ok(ReturnResultMsg.getVehicleDeliveryOrderPostingPms2Sap());
        }
        try{
            Map map = HttpUtil.sendPost(deliveryOrderInfo, Constant.PMS_SAP_VEHICLE_DELIVERY_ORDER_POSTING, Constant.PMS, COMM_URL);
            eaiLog.setRequestId(String.valueOf(map.get("requestId")));
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setEsbResultContent(JSONObject.toJSONString(map));
            eaiLog.setUrl(COMM_URL);
            Object object = map.get("header");
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(object));
            // jsonObject.get("statusFlag");
            String statusFlag=String.valueOf(jsonObject.get("statusFlag"));
            if (statusFlag.equals("0")){//这里只对ESB的处理状态做判断
                //处理失败，更状态位失败
                eaiLog.setDisposeStatus(2);
                apiResult = ResponseUtil.fail(Constant.SAP_R_CODE_FAIL,"["+Constant.PMS_SAP_VEHICLE_DELIVERY_ORDER_POSTING+"]");
            }else {
                //将返回的数据返给PMS
                JSONObject jsonResponse = JSONObject.parseObject(String.valueOf(map.get("response")));
                if (String.valueOf(jsonResponse.get("code")).equals("E")){
                    //处理失败，更状态位失败
                    eaiLog.setDisposeStatus(2);
                    apiResult=ResponseUtil.fail();
                }else {
                    apiResult = ResponseUtil.ok(map.get("response"));
                }
            }
        }catch (Exception e){
            //处理失败，更状态位失败
            eaiLog.setDisposeStatus(2);
            LOGGER.error(e.getMessage(),e);
            LOGGER.error("调用ESB系统失败===========");
            apiResult=ResponseUtil.fail();
        }
        //Message message = new Message(rocketConfig.getEaiLogTopic(), "eaiLog",(JSONObject.toJSONString(eaiLog)).getBytes() );
        try {
            // SendResult send = eaiLogProducer.getProducer().send(message);
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        }catch (Exception e){
            e.printStackTrace();
        }
        return apiResult;
    }


    /**
     * 整车VDC入库接口
     * @param order
     * @return
     */
    @Override
    public ApiResult vehicleInboundPms2Sap(VehicleInboundVdcVO order) {
      /*  if (true){
            order.setBudat("2019-07-01");
        }else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr=sdf.format(new Date());
            order.setBudat(dateStr);
        }*/
        /*  order.setLgort("VW01");
        order.setWerks("AS11");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr=sdf.format(new Date());
        order.setBudat(dateStr);*/
        String vehicleInboundVdcInfo = JSONObject.toJSONString(order);
        ApiResult apiResult=null;
        EaiLog eaiLog=new EaiLog();
        eaiLog.setPmsEaiContent(vehicleInboundVdcInfo);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("PMS系统发送整车VDC入库信息给SAP系统");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setServiceName(Constant.PMS_SAP_VEHICLE_INBOUND_VDC);
        if (esbSwitch.equals("false")) {
            return ResponseUtil.ok(ReturnResultMsg.getVehicleInboundPms2Sap());
        }
        try{
            Map map = HttpUtil.sendPost(vehicleInboundVdcInfo, Constant.PMS_SAP_VEHICLE_INBOUND_VDC, Constant.PMS, COMM_URL);
            eaiLog.setRequestId(String.valueOf(map.get("requestId")));
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setEsbResultContent(JSONObject.toJSONString(map));
            eaiLog.setUrl(COMM_URL);
            Object object = map.get("header");
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(object));
            // jsonObject.get("statusFlag");
            String statusFlag=String.valueOf(jsonObject.get("statusFlag"));
            if (statusFlag.equals("0")){//这里只对ESB的处理状态做判断
                //处理失败，更状态位失败
                eaiLog.setDisposeStatus(2);
                apiResult = ResponseUtil.fail(Constant.SAP_R_CODE_FAIL,"["+Constant.PMS_SAP_VEHICLE_INBOUND_VDC+"]");
            }else {
                //将返回的数据返给PMS
                JSONObject jsonResponse = JSONObject.parseObject(String.valueOf(map.get("response")));
                if (String.valueOf(jsonResponse.get("code")).equals("E")){
                    //处理失败，更状态位失败
                    eaiLog.setDisposeStatus(2);
                    apiResult=ResponseUtil.fail();
                }else {
                    apiResult = ResponseUtil.ok(map.get("response"));
                }
            }
        }catch (Exception e){
            //处理失败，更状态位失败
            eaiLog.setDisposeStatus(2);
            LOGGER.error(e.getMessage(),e);
            LOGGER.error("调用ESB系统失败===========");
            apiResult=ResponseUtil.fail();
        }
        // Message message = new Message(rocketConfig.getEaiLogTopic(), "eaiLog",(JSONObject.toJSONString(eaiLog)).getBytes() );
        try {
            // SendResult send = eaiLogProducer.getProducer().send(message);
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
        }
        return apiResult;
    }


    /**
     *  整车库存同步
     *  接口显示为移库单
     *
     */
    @Override
    public ApiResult vehicleStockShiftPms2Sap(VehicleStockShiftVO order) {
       /* if (true){
            order.setBudat("2019-07-01");
        }else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr=sdf.format(new Date());
            order.setBudat(dateStr);
        }*/
        /*SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr=sdf.format(new Date());
        order.setBudat(dateStr);
        order.setLgort("VW01");
        order.setUmlgo("VW01");
        order.setWerks("AS11");*/
        String vehicleStockShiftInfo = JSONObject.toJSONString(order);
        ApiResult apiResult=null;
        EaiLog eaiLog=new EaiLog();
        eaiLog.setPmsEaiContent(vehicleStockShiftInfo);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("PMS系统发送整车库存同步信息给SAP系统");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setServiceName(Constant.PMS_SAP_VEHICLE_STOCK_SHIFT);
        if (esbSwitch.equals("false")) {
            return ResponseUtil.ok(ReturnResultMsg.getVehicleStockShiftPms2Sap());
        }
        try{
            Map map = HttpUtil.sendPost(vehicleStockShiftInfo, Constant.PMS_SAP_VEHICLE_STOCK_SHIFT, Constant.PMS, SAP_URL);
            eaiLog.setRequestId(String.valueOf(map.get("requestId")));
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setEsbResultContent(JSONObject.toJSONString(map));
            eaiLog.setUrl(SAP_URL);
            Object object = map.get("header");
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(object));
            String statusFlag=String.valueOf(jsonObject.get("statusFlag"));
            if (statusFlag.equals("0")){//这里只对ESB的处理状态做判断
                //处理失败，更状态位失败
                eaiLog.setDisposeStatus(2);
                apiResult = ResponseUtil.fail(Constant.SAP_R_CODE_FAIL,"["+Constant.PMS_SAP_VEHICLE_STOCK_SHIFT+"]");
            }else {
                //将返回的数据返给PMS
                JSONObject jsonResponse = JSONObject.parseObject(String.valueOf(map.get("response")));
                if (String.valueOf(jsonResponse.get("code")).equals("E")){
                    //处理失败，更状态位失败
                    eaiLog.setDisposeStatus(2);
                    apiResult=ResponseUtil.fail();
                }else {
                    apiResult = ResponseUtil.ok(map.get("response"));
                }
            }
        }catch (Exception e){
            //处理失败，更状态位失败
            eaiLog.setDisposeStatus(2);
            LOGGER.error(e.getMessage(),e);
            LOGGER.error("调用ESB系统失败===========");
            apiResult=ResponseUtil.fail();
        }
        //  Message message = new Message(rocketConfig.getEaiLogTopic(), "eaiLog",(JSONObject.toJSONString(eaiLog)).getBytes() );
        try {
            //   SendResult send = eaiLogProducer.getProducer().send(message);
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        }catch (Exception e){
            e.printStackTrace();
        }
        return apiResult;
    }


    /**
     * 扫码出库信号同步(厂库)合并
     * 车辆出入库信息同步至TSP
     * pms->tsp
     */
    @Override
    public ApiResult vehicleStockStatusPms2Tsp(VehicleStockStatusVO order) {
        String vehicleStockStatusInfo = JSONObject.toJSONString(order);
        ApiResult apiResult=null;
        EaiLog eaiLog=new EaiLog();
        eaiLog.setPmsEaiContent(vehicleStockStatusInfo);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("PMS系统发送车辆出入库信息给TSP系统");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setServiceName(Constant.PMS_TSP_VEHICLE_STOCK_STATUS);
        if (esbSwitch.equals("false")) {
            return ResponseUtil.ok(ReturnResultMsg.vehicleStockStatusPms2Tsp());
        }
        try{
            Map map = HttpUtil.sendPost(vehicleStockStatusInfo, Constant.PMS_TSP_VEHICLE_STOCK_STATUS, Constant.PMS, COMM2_URL);
            eaiLog.setRequestId(String.valueOf(map.get("requestId")));
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setEsbResultContent(JSONObject.toJSONString(map));
            eaiLog.setUrl(COMM2_URL);
            Object object = map.get("header");
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(object));
            String statusFlag=String.valueOf(jsonObject.get("statusFlag"));
            if (statusFlag.equals("0")){//这里只对ESB的处理状态做判断
                //处理失败，更状态位失败
                eaiLog.setDisposeStatus(2);
                apiResult = ResponseUtil.fail(Constant.SAP_R_CODE_FAIL,"["+Constant.PMS_TSP_VEHICLE_STOCK_STATUS+"]");
            }else {
                //将返回的数据返给PMS
                //JSONObject jsonResponse = JSONObject.parseObject(String.valueOf(map.get("response")));

                apiResult = ResponseUtil.ok(map.get("response"));

            }
        }catch (Exception e){
            //处理失败，更状态位失败
            eaiLog.setDisposeStatus(2);
            LOGGER.error(e.getMessage(),e);
            LOGGER.error("调用ESB系统失败===========");
            apiResult=ResponseUtil.fail();
        }
        //Message message = new Message(rocketConfig.getEaiLogTopic(), "eaiLog",(JSONObject.toJSONString(eaiLog)).getBytes() );
        try {
            //  SendResult send = eaiLogProducer.getProducer().send(message);
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
        }
        return apiResult;
    }


    /**
     * 车辆实销信息
     * pms->tsp
     *
     */
    @Override
    public ApiResult vehicleCustomerSalesInfoPms2Tsp(@Validated CustomerSalesInfoVO order) {
        String customerSalesInfo = JSONObject.toJSONString(order);
        ApiResult apiResult=null;
        EaiLog eaiLog=new EaiLog();
        eaiLog.setPmsEaiContent(customerSalesInfo);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("PMS系统发送车辆实销信息给TSP系统");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setServiceName(Constant.PMS_TSP_VEHICLE_CUSTOMER_SALES_INFO);
        try{
            Map map = HttpUtil.sendPost(customerSalesInfo, Constant.PMS_TSP_VEHICLE_CUSTOMER_SALES_INFO, Constant.PMS, COMM2_URL);
            eaiLog.setRequestId(String.valueOf(map.get("requestId")));
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setEsbResultContent(JSONObject.toJSONString(map));
            eaiLog.setUrl(COMM2_URL);
            Object object = map.get("header");
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(object));
            // jsonObject.get("statusFlag");
            String statusFlag=String.valueOf(jsonObject.get("statusFlag"));
            if (statusFlag.equals("0")){//这里只对ESB的处理状态做判断
                //处理失败，更状态位失败
                eaiLog.setDisposeStatus(2);
                apiResult = ResponseUtil.fail(Constant.SAP_R_CODE_FAIL,"["+Constant.PMS_TSP_VEHICLE_CUSTOMER_SALES_INFO+"]");
            }else {
                //将返回的数据返给PMS
                JSONObject jsonResponse = JSONObject.parseObject(String.valueOf(map.get("response")));
                    apiResult = ResponseUtil.ok(map.get("response"));
            }
        }catch (Exception e){
            //处理失败，更状态位失败
            eaiLog.setDisposeStatus(2);
            LOGGER.error(e.getMessage(),e);
            LOGGER.error("调用ESB系统失败===========");
            apiResult = ResponseUtil.fail(Constant.SAP_R_CODE_EXP,"["+Constant.PMS_TSP_VEHICLE_CUSTOMER_SALES_INFO+"]");
        }
        try {
            OrderActualSalesReqVO var1=new OrderActualSalesReqVO();
            BeanUtils.copyProperties(order,var1);
            var1.setCreateRecordDate(order.getCreateRecord_date());
            var1.setOpenInvoiceDate(order.getOpenInvoice_date());
            var1.setDriverLicenseType(order.getDriver_license_type());
            var1.setDriverLicenseValidate(order.getDriver_license_validate());
            ApiResult upsResult = iamOrderActualSalesDubboServiceImpl.saveOrderActualSales(var1);
            if (upsResult.getCode()!=200){
                eaiLog.setDisposeStatus(3);
            }
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
            eaiLog.setDisposeStatus(3);
            LOGGER.error(e.getMessage(),e);
            LOGGER.error("调用ESB系统失败===========");
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
            apiResult = ResponseUtil.fail(Constant.SAP_R_CODE_EAI,"["+Constant.PMS_TSP_VEHICLE_CUSTOMER_SALES_INFO+"]");
        }
        return apiResult;
    }

   /*车辆过户*/
    @Override
    public ApiResult vehicleAssignedInfoPms2Tsp(AssignedInfoVO order) {
        String customerSalesInfo = JSONObject.toJSONString(order);
        ApiResult apiResult=null;
        EaiLog eaiLog=new EaiLog();
        eaiLog.setPmsEaiContent(customerSalesInfo);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("PMS系统发送车辆过户信息给TSP系统");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setServiceName(Constant.PMS_TSP_VEHICLE_ASSIGNED_INFO);
        try{
            Map map = HttpUtil.sendPost(customerSalesInfo, Constant.PMS_TSP_VEHICLE_ASSIGNED_INFO, Constant.PMS, TSP_TRANSFER_URL);
            eaiLog.setRequestId(String.valueOf(map.get("requestId")));
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setEsbResultContent(JSONObject.toJSONString(map));
            eaiLog.setUrl(TSP_TRANSFER_URL);
            Object object = map.get("header");
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(object));
            // jsonObject.get("statusFlag");
            String statusFlag=String.valueOf(jsonObject.get("statusFlag"));
            if (statusFlag.equals("0")){//这里只对ESB的处理状态做判断
                //处理失败，更状态位失败
                eaiLog.setDisposeStatus(2);
                apiResult = ResponseUtil.fail(Constant.SAP_R_CODE_FAIL,"["+Constant.PMS_TSP_VEHICLE_ASSIGNED_INFO+"]");
            }else {
                //将返回的数据返给PMS
                JSONObject jsonResponse = JSONObject.parseObject(String.valueOf(map.get("response")));
                if (!String.valueOf(jsonResponse.get("code")).equals("200")){
                    //处理失败，更状态位失败
                    eaiLog.setDisposeStatus(2);
                    apiResult=ResponseUtil.fail();
                }else {
                    apiResult = ResponseUtil.ok(map.get("response"));
                }
            }
        }catch (Exception e){
            //处理失败，更状态位失败
            eaiLog.setDisposeStatus(2);
            LOGGER.error(e.getMessage(),e);
            LOGGER.error("调用ESB系统失败===========");
            apiResult=ResponseUtil.fail();
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
        }
        return apiResult;
    }

}
